package com.example.springjishi.controller;


import com.example.springjishi.pojo.Car;
import com.example.springjishi.pojo.CarType;
import com.example.springjishi.service.CarService;
import com.example.springjishi.service.CarTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class CarController {

    @Autowired
    private CarService carService;

    @Autowired
    private CarTypeService carTypeService;

    @GetMapping("/list")
    public String selectCarPageList(Model model, Car car, @RequestParam(defaultValue = "1") Integer pageNo) {
        List<CarType> carTypes = carTypeService.selectCarTypes();

        Integer pageSize = 3;

        Integer startIndex = (pageNo - 1) * pageSize;

        List<Car> cars = carService.selectCarList(car, startIndex, pageSize);

        Integer carCounts = carService.selectCarCount(car);

        Integer carPages = carCounts / pageSize;
        if (carCounts % pageSize > 0) {
            carPages++;
        }

        model.addAttribute("carTypes", carTypes);
        model.addAttribute("pageNo", pageNo);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("cars", cars);
        model.addAttribute("carCounts", carCounts);
        model.addAttribute("carPages", carPages);

        return "list";
    }

    @GetMapping("/modify")
    public String modifyCar(Model model, Integer carId) {
        Car car = carService.selectCar(carId);

        model.addAttribute("car", car);

        return "modify";
    }

    @PostMapping("/modify")
    public String modifyCar(Car car) {
        if (carService.modifyCar(car) > 0) {
            return "redirect:/list";
        } else {
            return "error";
        }
    }
}
